import React, {Component} from 'react'
import T from 'prop-types'

import { Spin,message,Modal } from 'antd';

import '../../../../css/myBlog/rightContainer/weibo.less'

import { WeaRichText } from 'ecCom'

import WeiboBar from "./WeiboBar"

import ComVar from "../ComVar"
const {PublicRangeType, ComeFrom} = ComVar

import WeaUtils from "../../../Component/wea-utils"
const {DateFormat} = WeaUtils

import Mood from "./Mood"
import "./WeiboEdit.less"

import * as Util from '../../../../util/index'
import Dict from '../../../Component/wea-blog-dict';

const mirror = Dict.bottomBarMirror;

class WeiboEdit extends Component {
    static contextTypes = {
        router: T.routerShape
    }

    constructor(props) {
        super(props)
        this.state = {
            editing: false,
            authType: PublicRangeType.public,
            authRange: [],
            mood: "1",
            status: '',
            richValue: '',
        }
        this.CKE_ID = `wea_ckeditor_weibo_${props.blogType}_edit`
        this.onTempletChange = this.onTempletChange.bind(this);
    }
    componentWillReceiveProps(nextProps){
    	const { defaultTemplate } = this.props;
    	if(!nextProps.hasSubmited && defaultTemplate && defaultTemplate.tempContent && nextProps.defaultTemplate && nextProps.defaultTemplate.tempContent && defaultTemplate.tempContent !==  nextProps.defaultTemplate.tempContent){
    		this.setState({richValue: nextProps.defaultTemplate.tempContent});
    	}
    }
    
    render() {
        let {editing, authType, authRange, status, richValue} = this.state,
            {hasSubmited, defaultTemplate, weiboCKEditorConfig} = this.props;
        //暂时接入过来 zxt
        let bottomBarConfig = [];
        let uploadUrl = '';
        weiboCKEditorConfig && weiboCKEditorConfig.map(cg => {
        	cg.name === 'selects' && bottomBarConfig.push({
        		name: 'Component', 
        		show: <Mood onSelect={mood => this.setState({mood})}/>
        	})
        	cg.name === 'dialogs' && cg.items.map(item => {
        		let obj = { 
	        		isBlog: true,
	        		name: 'Browser', 
	        		show: <div className="wea-cb-item">
	                    <span className={`wea-cbi-icon ${mirror[item].icon}`}/>
	                    <span className="wea-cbi-text">{mirror[item].name}</span>
	                </div>,
	        		type: mirror[item].type, 
	        		title: mirror[item].name,
	        		isSingle: item === 'Templet',
	        	};
	        	if(item === 'Templet') obj.onToolsChange = this.onTempletChange
	        	bottomBarConfig.push(obj);
	        })
        	cg.name === 'uploads' && cg.items.map(item => {
	        	bottomBarConfig.push({ 
	        		isBlog: true,
	        		name: 'Upload', 
	        		show: <div className="wea-cb-item">
	        	        <span className='wea-cbi-icon icon-blog-Enclosure'/>
	        	        <span className="wea-cbi-text">附件</span>
	        	    </div>,
	        		uploadId: 'webo_edit', 
	        		uploadUrl: `${item.Attachment.uploadUrl}?category=${item.Attachment.position}`, 
	        		category: item.Attachment.position, 
	        		maxUploadSize: item.Attachment.maxSize,
	        		style: {display: "inline-block", padding: 0}
	        	})
	        	uploadUrl = `${item.Attachment.uploadUrl}?category=${item.Attachment.position}`;
	        })
        })
        //暂时接入过来 zxt
        return (
            <div className='wea-ckeditor-import-ecCom'>
            	<WeaRichText 
            		id={this.CKE_ID}
                    ref={this.CKE_ID}
                    ls={true}
                    value={!hasSubmited && defaultTemplate.tempContent && !localStorage[`wea_rich_text_ls_${this.CKE_ID}`] ? defaultTemplate.tempContent : richValue}
                    ckConfig={{
                    	toolbar:[
				            { name: 'document', items: [ 'Source'] },
				            { name: 'paragraph', items: [ 'JustifyLeft', 'JustifyCenter', 'JustifyRight', '-', 'NumberedList', 'BulletedList' ] },
				            { name: 'styles', items: [ 'Format', 'Font', 'FontSize' ] },
				            { name: 'colors', items: [ 'TextColor' ] },
				            { name: 'basicstyles', items: [ 'Bold', 'Italic', 'Underline', 'Strike', ] },
				            { name: 'insert', items: [ 'Image', 'Table', 'Smiley'] }
				        ],
				        extraPlugins: 'autogrow',
                        height:150,
                        autoGrow_minHeight: 150,
                        autoGrow_maxHeight: 600,
                        removePlugins: 'resize',
                        uploadUrl: '/api/blog/fileupload/uploadimage',
                    }}
                    extentsConfig
                    bottomBarConfig={ bottomBarConfig }
                    bootomBarStyle={{}}
                    onChange={v=>this.setState({richValue: v})}
                    onStatusChange={s => this.setState({status: s})}
                    onToolsChange={Util.transfStr}
            	/>
		        {
		        	status === 'ready' && <WeiboBar
			            authType={authType}
			            authRange={authRange}
			            onAuthType={this.onAuthType}
			            onAuthRange={this.onAuthRange}
			            publishClick={this.publishWeibo}
			            style={{borderTop: "none", padding: "10px 16px 8px 16px", marginBottom: "16px"}}
			        />
		        }
            </div>

        )
    }
    onTempletChange(name, ids, list, type){
    	let { richValue } = this.state; 
    	Util.templetChange(richValue,v => this.setState({richValue: v}), name, ids, list, type)
    }
//  <WeaCkEditor
//      id={this.CKE_ID}
//      ref={this.CKE_ID}
//      onReady={this.onReady}
//      content={(!hasSubmited && defaultTemplate.tempContent ? defaultTemplate.tempContent : "")}
//      type="blog"
//      config={{
//          extraPlugins: 'autogrow',
//          height:200,
//          autoGrow_minHeight: 200,
//          autoGrow_maxHeight: 600,
//          //autoGrow_bottomSpace: 50,
//          removePlugins: 'resize'
//      }}
//      configBar={weiboCKEditorConfig}
//      // onBlur={() => {
//      //     this.refs[this.CKE_ID] && this.refs[this.CKE_ID].CleanEditor()
//      // }}
//  />

    onAuthType = (authType) => {
        this.setState({authType: authType})
    }

    onAuthRange = (authRange) => {
        this.setState({authRange: authRange})
    }

    publishWeibo = () => {
        let {authType, authRange, mood, richValue} = this.state,
            {blogType, actions, user} = this.props,
            workdate = DateFormat(new Date(), "yyyy-MM-dd")
        let ckref = this.refs[this.CKE_ID];
        if (!ckref.checkMode()) {
            message.error("不能以源码模式或markdown模式保存，请将编辑器切换到可视化模式");
            return;
        }
        localStorage.removeItem(`wea_rich_text_ls_${this.CKE_ID}`)
        actions.editWeibo(
            {
                appItemId: mood || "1",
                comefrom: ComeFrom.pc,
                content: richValue,
                workdate: workdate
            },
            {
                type: blogType,
                workdate: workdate
            },
            result => {
                if (result.status == "1") {
                    actions.getBasicInfo()
                }
            }
        )
        this.refs[this.CKE_ID].setData('');
    }

    onReady = () => {
        this.setState({editing: true, richValue: ''})
    }
}

export default WeiboEdit